import gtk
import os.path
#import StringIO
import utils
import xmmsclient

MARKUP = 1

class BroadcastManager:
    active_pos = None
    iters_pool = []
    
    def __init__(self, aidem, xmms2):
        treeview = aidem.get_widget("treeview1")
        model = treeview.get_model()
        self.aidem = aidem
        self.model = model
        self.progressbar = aidem.get_widget("hscale1")
        self.xmms2 = xmms2
        xmms2.playback_current_id(self.on_current_id_changed)
        xmms2.playlist_current_active(self.on_playlist_loaded)
        xmms2.broadcast_playback_current_id(self.on_current_id_changed)
        xmms2.broadcast_playlist_changed(self.on_playlist_changed)
        xmms2.broadcast_playlist_current_pos(self.playlist_current_pos_update)
        xmms2.broadcast_playlist_loaded(self.on_playlist_loaded)
        xmms2.signal_playback_playtime(self.update_playtime)

    def get_playtime(self, res):
        if res.iserror():
            print "[BroadcastManager] get_playtime error"
            return
        tag = res.value()
        duration = tag["duration"]
        self.progressbar.set_range(0, duration)

    def insert_entry(self, res):
        if res.iserror():
            print "[BroadcastManager] error retrieving medialib info"
        info = res.value()
        values = []
        for k in "url", "title", "artist", "album", "picture_front", "id":
            try:
                v = info[k]
            except KeyError:
                v = ""
            values.append(v)
        url, title, artist, album, picture_front, _id = values
        id = int(_id)
        markup = utils.make_markup(url, title, artist, album)
        pb = None
        if picture_front:
            iter = self.model.append([pb, markup, id, True])
            self.iters_pool.append(iter)
            self.xmms2.bindata_retrieve(picture_front, self.set_cover)
        else:
            self.model.append([pb, markup, id, True])

    def load_playlist(self, res):
        if res.iserror():
            print "[BroadcastManager] error retrieving playlist contents"
        ids = res.value()
        for i in ids:
            self.xmms2.medialib_get_info(i, self.insert_entry)
        
    def on_current_id_changed(self, res):
        if res.iserror():
            print "[BroadcastManager] error broadcasting current id"
            return
        id = res.value()
        self.xmms2.medialib_get_info(id, cb=self.get_playtime)

    def on_playlist_changed(self, res):
        if res.iserror():
            print "[BroadcastManager] Error retrieving playlist changed signal"
        info = res.value()
        type = info["type"]
        playlist = info["name"]
        if type == xmmsclient.PLAYLIST_CHANGED_ADD:
            position = info["position"]
            id = info["id"]
            self.xmms2.medialib_get_info(id, self.insert_entry)
        elif type == xmmsclient.PLAYLIST_CHANGED_CLEAR:
            self.model.clear()
        elif type == xmmsclient.PLAYLIST_CHANGED_INSERT:
            print info
        elif type == xmmsclient.PLAYLIST_CHANGED_MOVE:
            position = info["position"]
            newposition = info["newposition"]
            id = info["id"]
            pos_iter = self.model.get_iter(position)
            newpos_iter = self.model.get_iter(newposition)
            if position < newposition:
                self.model.move_after(pos_iter, newpos_iter)
            else:
                self.model.move_before(pos_iter, newpos_iter)
        elif type == xmmsclient.PLAYLIST_CHANGED_REMOVE:
            position = info["position"]
            #print "removing", position
            del self.model[position]
        elif type == xmmsclient.PLAYLIST_CHANGED_SHUFFLE:
            print info
        elif type == xmmsclient.PLAYLIST_CHANGED_SORT:
            print info
        elif type == xmmsclient.PLAYLIST_CHANGED_UPDATE:
            print info

    def on_playlist_loaded(self, res):
        if res.iserror():
            print "[BroadcastManager]  Could nod broadcast playlist loaded"
        playlist_id = res.value()
        self.xmms2.playlist_list_entries(playlist_id, cb=self.load_playlist)

    def playlist_current_pos_update(self, res):
        if res.iserror():
            print "[BroadcastManager] could not update current position"
            return
        playlist_info = res.value()
        name = playlist_info["name"]
        position = playlist_info["position"]
        old_pos = self.active_pos
        try:
            markup = self.model.get_value(old_pos, MARKUP)
            new_markup = utils.unbold(markup)
            self.model.set(old_pos, MARKUP, new_markup)
        except Exception, e:
            #print "in", e
            pass
        i_pos = int(position)
        try:
            self.active_pos = self.model.get_iter(i_pos)
        except Exception, e:
            #print "out", e
            self.active_pos = None
            return
        markup = self.model.get_value(self.active_pos, MARKUP)
        new_markup = utils.bold(markup)
        self.model.set(self.active_pos, MARKUP, new_markup)
        
    def save_cover(self):
        #Todo: Find the covers on the web. Maybe unnecessary if xmms2
        #services becomes a reality in Ubuntu
        return

    def set_cover(self, res):
        if res.iserror():
            print "[BroadcastManager] Could not set cover"
            return
        cover = res.value()
        loader = gtk.gdk.PixbufLoader()
        loader.set_size(utils.THUMBNAILS_SIZE, utils.THUMBNAILS_SIZE)
        loader.write(cover)
        loader.close()
        pb = loader.get_pixbuf()
        iter = self.iters_pool.pop(0)
        self.model.set(iter, 0, pb)
        
    def update_playtime(self, res):
        if res.iserror():
            print "[BroadcastManager] Could not update playtime"
            res.restart()
            return
        elif self.aidem.progressbar_pressed:
            res.restart()
            return
        playtime = res.value()
        self.progressbar.set_value(playtime)
        res.restart()
